package android.medicalcloud.com.yiapp.yilian.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.medicalcloud.com.yiapp.R;
import android.medicalcloud.com.yiapp.base.activity.BaseActivity;
import android.medicalcloud.com.yiapp.base.net.lisener.ViewNetCallBack;
import android.medicalcloud.com.yiapp.base.utils.Logger;
import android.medicalcloud.com.yiapp.base.utils.StringTools;
import android.medicalcloud.com.yiapp.yilian.configer.enums.HttpConfig;
import android.medicalcloud.com.yiapp.yilian.im.model.FriendshipInfo;
import android.medicalcloud.com.yiapp.yilian.logic.CommonController;
import android.medicalcloud.com.yiapp.yilian.logic.OrderController;
import android.medicalcloud.com.yiapp.yilian.logic.PushController;
import android.medicalcloud.com.yiapp.yilian.model.VersionModel;
import android.medicalcloud.com.yiapp.yilian.ui.view.NoScrollViewPager;
import android.medicalcloud.com.yiapp.yilian.ui.view.adapter.MainPagerAdapter;
import android.medicalcloud.com.yiapp.yilian.ui.view.dialog.VersionDialog;
import android.medicalcloud.com.yiapp.yilian.utils.android.JsonTool;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import java.io.Serializable;

/**
 * Created by wanggenlin on 17-5-18.
 */
public class MainPageActivity extends BaseActivity implements ViewNetCallBack{
    TabLayout tabLayout;
    NoScrollViewPager viewPager;
    TextView titleText;
    CheckBox homecheckbox;
    CheckBox ordercheckbox;
    CheckBox datecheckbox;
    CheckBox personcheckbox;
    MainPagerAdapter adapter;
    String[] titles = new String[]{"首页", "订单", "日程", "我的"};
    View mainToolbar;

    VersionDialog versionDialog;

    private Toast toast;

    public static  String action="MainPage.Chanage.Index";

    @Override
    protected void initView() {
        tabLayout = (TabLayout)findViewById(R.id.tabLayout);
        viewPager = (NoScrollViewPager)findViewById(R.id.viewPager);
        titleText = (TextView)findViewById(R.id.titleText);
        homecheckbox = (CheckBox)findViewById(R.id.homecheckbox);
        ordercheckbox = (CheckBox)findViewById(R.id.ordercheckbox);
        datecheckbox = (CheckBox)findViewById(R.id.datecheckbox);
        personcheckbox = (CheckBox)findViewById(R.id.personcheckbox);
        mainToolbar = findViewById(R.id.mainToolbar);
        versionDialog = new VersionDialog(this);
        Logger.e("connect====="+isNetworkAvailable(this));
        findViewById(R.id.netErrorToastTv).setVisibility(isNetworkAvailable(this)?View.VISIBLE:View.GONE);
        toast = Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT);

    }
    private void quitToast() {
        if (null == toast.getView().getParent()) {
            toast.show();
        } else {
            finish();
//            System.exit(0);
        }
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        OrderController.getInstance().toast(this);
        FriendshipInfo.getInstance().refresh(true);
    }

    @Override
    protected void initData() {
        viewPager.setOffscreenPageLimit(10);
        adapter = new MainPagerAdapter(getSupportFragmentManager(), this);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabsFromPagerAdapter(adapter);

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub
                titleText.setText(titles[arg0]);

                setDefault();
                switch (arg0) {
                    case 0:
                        homecheckbox.setChecked(true);
                        break;
                    case 1:
                        ordercheckbox.setChecked(true);
                        mainToolbar.setVisibility(View.GONE);
                        break;
                    case 2:
                        datecheckbox.setChecked(true);
                        mainToolbar.setVisibility(View.GONE);
                        findViewById(R.id.netErrorToastTv).setVisibility(View.GONE);
                        break;
                    case 3:
                        personcheckbox.setChecked(true);
                        mainToolbar.setVisibility(View.GONE);
                        break;
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });
        setDefault();
        homecheckbox.setChecked(true);
        homecheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(0);
                setDefault();
                homecheckbox.setChecked(true);
            }
        });
        ordercheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(1);

                setDefault();
                ordercheckbox.setChecked(true);
                mainToolbar.setVisibility(View.GONE);
            }
        });
        datecheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setDefault();
                findViewById(R.id.netErrorToastTv).setVisibility(View.GONE);
                viewPager.setCurrentItem(2);

                datecheckbox.setChecked(true);
                mainToolbar.setVisibility(View.GONE);
            }
        });
        personcheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(3);
                setDefault();
                personcheckbox.setChecked(true);
                mainToolbar.setVisibility(View.GONE);
            }
        });
        PushController.getInstance().bind();

        CommonController.getInstance().versionCheck(this);


        reiver = new ChanageReiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(action);
        registerReceiver(reiver,intentFilter);

        int index = getIntent().getIntExtra("index",-1);
        Logger.e("index    "+index);
        if (index!=-1){
            viewPager.setCurrentItem(index);
        }

    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(reiver);
        super.onDestroy();
    }

    ChanageReiver reiver;
    private void setDefault() {
        homecheckbox.setChecked(false);
        ordercheckbox.setChecked(false);
        datecheckbox.setChecked(false);
        personcheckbox.setChecked(false);
        mainToolbar.setVisibility(View.VISIBLE);
        findViewById(R.id.netErrorToastTv).setVisibility(isNetworkAvailable(this)?View.VISIBLE:View.GONE);
        Logger.e("connect====="+isNetworkAvailable(this));
    }
    /**
     * 检测当的网络（WLAN、3G/2G）状态
     * @param context Context
     * @return true 表示网络可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected())
            {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED)
                {
                    // 当前所连接的网络可用
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.ac_main;
    }

    @Override
    public void onConnectStart(Object o) {

    }

    @Override
    public void onConnectEnd() {

    }

    @Override
    public void onFail(Exception e, Object o, String reslut) {

    }

    @Override
    public void onData(Serializable result, int flag, boolean fromNet, Object o) {

        if (flag== HttpConfig.orderToast.getType()){

            String count = JsonTool.getString(o.toString(),"count");
            if (StringTools.isNullOrEmpty(count)){
                findViewById(R.id.tabUnread).setVisibility(View.GONE);
                return;
            }
            if (count.equals("0")){
                findViewById(R.id.tabUnread).setVisibility(View.GONE);
                return;
            }
            findViewById(R.id.tabUnread).setVisibility(View.VISIBLE);
        }

        if (flag==HttpConfig.versionUpdate.getType()){
            Logger.e(o.toString()+"============version=====");
            VersionModel model = (VersionModel)result;
            Logger.e(o.toString()+"============version====="+model.getIsUpdate());
            if (model.getIsUpdate().equals("1")){
                versionDialog.setRes(model.getApp().getUrl(),model.getApp().getPrompt(),model.getApp().getIsMandatory().equals("1"));
                versionDialog.show();
            }
        }
    }


    public class ChanageReiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            viewPager.setCurrentItem(1);

        }
    }

    /**
     * 双击两次退出程序提示  第三种方式
     * <p/>
     * https://github.com/QQ986945193
     */
    // 1.on..2.开发者实现 3.系统调用
    // 条件 :点击物理键盘或者软件盘
    // int keyCode按键编号
    long[] times = new long[2];

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // ①　找出回调函数
            // ②　点击时间 time1 time2
            // ③　时间 间隔 <2000 退出
            // ④　提示再点一次
            times[0] = times[1];
            times[1] = System.currentTimeMillis();
            if (times[1] - times[0] < 2000) {
                finish();
            } else {
                Toast.makeText(getBaseContext(), "再点一次退出", Toast.LENGTH_SHORT).show();
            }
            return true;// 消费事件
        }

        return super.onKeyDown(keyCode, event);
    }
}
